package iosr11.gbase;

import iosr11.data.Student;
import iosr11.data.StudentImpl;
import iosr11.gcontacts.Contacts;

import java.net.URL;

import com.google.api.gbase.client.FeedURLFactory;
import com.google.api.gbase.client.GoogleBaseEntry;
import com.google.api.gbase.client.GoogleBaseFeed;
import com.google.api.gbase.client.GoogleBaseQuery;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.contacts.ContactEntry;

public class StudentBaseImpl implements StudentBase{

	private BaseDAO engine;
	private Contacts contacts;
	
	public StudentBaseImpl(BaseDAO engine, Contacts contacts){
		this.engine = engine;
		this.contacts = contacts;
	}
	

	@Override
	public Contacts getContactsService() {
		return contacts;
	}


	@Override
	public boolean addNewStudent(String realLifeName, String email,
			int indexNumber) {
		String userId = contacts.addNewUserReturnId(realLifeName, email);
		if (userId == null)
			return false;
		GoogleBaseEntry entry = new GoogleBaseEntry();
		entry.setTitle(new PlainTextConstruct("student"));
		entry.setDraft(true);
		entry.getGoogleBaseAttributes().setItemType("System student");
		entry.getGoogleBaseAttributes().addIntAttribute("index number", indexNumber);
		//System.out.println(userId);
		entry.getGoogleBaseAttributes().addTextAttribute("user", userId);
		
		return this.addNewStudentToBase(entry);
	}


	@Override
	public boolean addNewStudentToBase(GoogleBaseEntry entry) {
		return engine.addRecord(entry);
	}


	@Override
	public Student getStudent(String username) {
		// TODO Nie sprawdza czy student
		ContactEntry contact = contacts.getUser(username);
		if (contact == null)
			return null;
		String userId = contact.getId();
		
		GoogleBaseQuery query = new GoogleBaseQuery(FeedURLFactory.getDefault().getItemsFeedURL());
		GoogleBaseFeed feed = engine.getQueryResult(query, "user", userId);
		if (feed==null)
			return null;
		if (feed.getEntries().size()!=1)
			return null;
		//ArrayList<String> groups
		
		return new StudentImpl(contact.getTitle().getPlainText(),
				contact.getEmailAddresses().get(0).getAddress(),
				feed.getEntries().get(0).getGoogleBaseAttributes().getIntAttribute("index number"),
				feed.getEntries().get(0).getId(),
				null);
	}

	@Override
	public GoogleBaseEntry getStudent(URL url) {
		// TODO Auto-generated method stub
		return null;
	}

}
